<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="项目类型" prop="projectType">
        <el-select v-model="queryParams.projectType" placeholder="请选择项目类型" clearable style="width: 200px">
          <el-option v-for="dict in project_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>


      <el-form-item label="销售负责人" prop="saleRole">
        <el-select @change="handleQuery" v-model="queryParams.saleRole" placeholder="请选择" clearable
          style="width: 200px">
          <el-option v-for="dict in saleRoleList" :key="dict.participantId" :label="dict.participanName"
            :value="dict.participantId" />
        </el-select>
      </el-form-item>


      <el-form-item label="关键字搜索" prop="keyWords">
        <el-input v-model="queryParams.keyWords" placeholder="请输入关键字" clearable @keyup.enter="handleQuery" />
      </el-form-item>


      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>



    </el-form>
    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    <div style="justify-content: flex-start;" v-if="userStore.name == 'xuhb'">
      <el-checkbox-group v-model="selectedProps">
        <el-checkbox v-for="col in allColumns" :key="col.prop" :label="col.prop">
          {{ col.label }}
        </el-checkbox>
      </el-checkbox-group>
      <el-button type="primary" plain style="margin: 10px;" @click="saveColumnConfig">保存配置</el-button>
    </div>

    <el-row v-loading="loadingCount" element-loading-text="数据统计中..." :gutter="userStore.isMobile ? 10 : 24"
      class="statistic-row">
      <el-col :span="userStore.isMobile ? 24 : 8">
        <div class="statistic-card">
          <el-statistic :value="contractAmountTotal" :formatter="(value) => value.toFixed(2)">
            <template #title>
              <div style="display: inline-flex; align-items: center;font-size: 16px;">
                合同金额￥
              </div>
            </template>
          </el-statistic>
        </div>
      </el-col>

      <el-col :span="userStore.isMobile ? 24 : 8">
        <div class="statistic-card">
          <el-statistic :value="settlementAmountTotal" :formatter="(value) => value.toFixed(2)">
            <template #title>
              <div style="display: inline-flex; align-items: center;font-size: 16px;">
                结算金额￥
              </div>
            </template>
          </el-statistic>
        </div>
      </el-col>

      <el-col :span="userStore.isMobile ? 24 : 8">
        <div class="statistic-card">
          <el-statistic :value="receivedTotal" :formatter="(value) => value.toFixed(2)">
            <template #title>
              <div style="display: inline-flex; align-items: center;font-size: 16px;">
                实收金额￥
              </div>
            </template>
          </el-statistic>
        </div>
      </el-col>
    </el-row>


    <el-table v-loading="loading" :data="projectList" border>
      <el-table-column v-for="col in visibleColumns" :key="col.prop" :prop="col.prop" :label="col.label"
        :align="'center'"
        :show-overflow-tooltip="['contractAmount', 'settlementAmount', 'housekeeperName'].includes(col.prop)"
        :width="getWidth(col.prop)">
        <!-- 特殊列的插槽处理 -->
        <template #default="scope" v-if="['approvalDate', 'planDate', 'acceptTime'].includes(col.prop)">
          <span>{{ parseTime(scope.row[col.prop], "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <!-- 固定操作列 -->
      <el-table-column label="操作" fixed="right" :width="userStore.isMobile ? 80 : 220" align="center"
        class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" :icon="userStore.isMobile ? '' : 'View'"
            @click="handleView(scope.row)">查看</el-button>
          <el-button link type="primary" @click="handles(scope.row)">去处理</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <el-dialog v-model="openView" fullscreen append-to-body>
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="项目信息" name="first">
          <projectView :key="'projectView' + form.projectNo" :datas="form" :isView="isView" :column="3" :sizes="'large'"
            :personList="personList" :attachmentList="attachmentList" :payList="payList" :warrantyList="warrantyList"
            :implementList="implementList" :accountingList="accountingList"></projectView>
        </el-tab-pane>
        <el-tab-pane label="正式清单" name="second">
          <mainList v-if="activeName == 'second'" :datas="form"></mainList>
        </el-tab-pane>
        <el-tab-pane label="管家婆出库单" name="third">
          <saleList v-if="activeName == 'third'" :datas="form"></saleList>
        </el-tab-pane>
        <el-tab-pane label="费用汇总" name="four">
          <feeList v-if="activeName == 'four'" :datas="form"></feeList>
        </el-tab-pane>
        <el-tab-pane label="清单对比" name="five">
          <compareMainAndSale v-if="activeName == 'five'" :datas="form"></compareMainAndSale>
        </el-tab-pane>
        <el-tab-pane label="配套施工清单" name="seven">
          <matching v-if="activeName == 'seven'" :datas="form"></matching>
        </el-tab-pane>


      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Project">
import {
  listProject,
  getProject,
  delProject,
  addProject,
  updateProject,
  syncData,
  getCompanyList,
  listCompany,
  listParticipan, getParticipan, delParticipan, addParticipan, updateParticipan, getStatus, getAllSaleRole,
  saveUserTableConfig, getUserTableConfig, myJoinProject, myJoinListCount, listAccounting, listAttachment, listPay, listWarranty, listImplement
} from "@/api/project/project";
import {
  Plus
} from '@element-plus/icons-vue'
import { getInfo } from "@/api/login";
import { listAllUser, getUser } from "@/api/system/user";
import {
  getCheck, getNextPermission, listDictionary, getDictionary, delDictionary, addDictionary,
  updateDictionary, listAllDictionary

} from "@/api/project/dictionary";
import { useRouter } from 'vue-router';


const router = useRouter();
const route = useRoute();

function handles(row, types) {
  console.log("首页跳转", row);
  if (row.phaseId == "3") {//项目实施
    router.push({
      path: '/implement/projectImplement',
      query: {
        projectNo: row.projectNo,
      }
    });

  }
  else if (row.phaseId == "4") {//项目验收
    router.push({
      path: '/accept/projectAccept',
      query: {
        projectNo: row.projectNo,
      }
    });
  }
  else if (row.phaseId == "5") {//项目核算
    router.push({
      path: '/projectAccounting/accounting',
      query: {
        projectNo: row.projectNo,
      }
    });
  }
  else if (row.phaseId == "2") {//立项前期
    router.push({
      path: '/approve/projecPreMange',
      query: {
        projectNo: row.projectNo,
      }
    });
  } else if (row.phaseId == "1") {//项目立项
    router.push({
      path: '/project/projectManage',
      query: {
        projectNo: row.projectNo,
      }
    });
  }
  else if (row.phaseId == "6") {
    router.push({
      path: '/warranty/projectWarranty',
      query: {
        projectNo: row.projectNo,
      }
    });
  }
  else {
    proxy.$modal.msgError("暂无待处理数据");
  }
}

const haveNext = ref(false)
const { proxy } = getCurrentInstance();
const { project_type } = proxy.useDict("project_type");
const { company_type } = proxy.useDict("company_type");


const posts = ref([])
const userList = ref([])
const projectList = ref([]);
const attachmentList = ref([]);
const payList = ref([]);
const personList = ref([]);
const accountingList = ref([]);
const implementList = ref([]);
const logs = ref([]);
const warrantyList = ref([]);

const companyList = ref([]);
const open = ref(false);
const isView = ref(false);
const openView = ref(false);
const openOper = ref(false);
const openPhase = ref(false);
const loading = ref(true);
const loadingCount = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeAcceptTime = ref([]);
const projectNo = ref(null)
const phasetList = ref([]);
const formDisabled = ref(true);
const currentIndex = ref(0)
const currentType = ref('')
const status = ref("1")
const currenrPhaseId = ref()
const loadingQuery = ref(false)
let currentPhase = reactive({
  phaseCode: '',
});
const source = ref(0)
const source1 = ref(0)
const source2 = ref(0)
const contractAmountTotal = useTransition(source, {
  duration: 1500,
})
const settlementAmountTotal = useTransition(source1, {
  duration: 1500,
})
const receivedTotal = useTransition(source2, {
  duration: 1500,
})



import projectView from "../projectView.vue";
import { ref } from "vue";
import { updatePhase, addPhase } from "../../../api/project/project";
import { useTransition } from '@vueuse/core'


const data = reactive({
  currentProject: {},
  form: {
    createUserName: null,
    createUserId: null,
    createDeptName: null,
    createDept: null,
  },
  currentConfig: {//当前环节关联的配置表

  },
  personForm: {
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // status:2,//写死 查询上个阶段已完成的就进入立项前期阶段 1是进行中 2是已完成 
    // 新建项目的时候会默认插入一条立项阶段到立项表 点击下一步的时候会更新阶段表把当前项目当前阶段的状态
    //改为已完成  同时往阶段表插入下一个阶段 状态是1 进行中
    //   phaseId: 1,//阶段字典id   1是立项 2是立项前期 3是实施 .....现在是立项阶段 查询所有已立项的项目 完成未完成都可查
    projectName: null,
    projectAmount: null,
    projectType: null,
    saleRole: null,
    projectUnit: null,
    acceptTime: null,
    customerName: null,
    housekeeperName: null,
    phaseCode: null,
    minProjectAmount: null,
    maxProjectAmount: null,
    keyWords: null
  },
  rules: {
    projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
    approvalDate: [{ required: true, message: "立项日期不能为空", trigger: "blur" }],
    projectType: [{ required: true, message: "项目类型 不能为空", trigger: "blur" }],
    // contractAmount: [{ required: true, message: "合同金额不能为空", trigger: "blur" }],

  },
  personRules: {
    postId: [{ required: true, message: "岗位不能为空", trigger: "blur" }],
    participantId: [{ required: true, message: "参与人不能为空", trigger: "blur" }],
  }

});


function getCurrPhase(projectNo) {
  let currPhase = {
    projectNo: projectNo,
    phaseId: 1//立项阶段 
  }
  getStatus(currPhase).then((response) => {
    console.log("当前阶段信息", response);
    if (response.data == null) {//没有查询到阶段信息  可以点击下一步 插入阶段信息

    } else {
      status.value = response.data.status
      currenrPhaseId.value = response.data.id
    }
  });
}




const { queryParams, form, rules, personForm, personRules, currentConfig } = toRefs(data);

const setHousekeeperName = (id) => {

  if (id == undefined) {
    form.value.housekeeperName = '';
    return
  }
  const filteredObjects = companyList.value.find((obj) => obj.id === id);
  form.value.housekeeperName = '';
  console.log("filteredObjects", filteredObjects);
  form.value.housekeeperName = filteredObjects?.companyName || '';
  console.log("setHousekeeperName", id, form.value.housekeeperName);
}


function selectCompany(query) {
  console.log("queryquery", query);
  loadingQuery.value = true
  let params = {
    companyName: query
  }
  listCompany(params).then((response) => {
    companyList.value = response.data
    loadingQuery.value = false
  });

}

function tets() {
  getUser().then(response => {
    posts.value = response.posts;
    console.log("岗位1111", response);
  });
  listAllUser().then(res => {
    console.log("userlist", res);
    userList.value = res
  });

}

const saleRoleList = ref([])

/** 查询绩效基本信息列表 */
async function getList() {

  const type = route.query.type;
  console.log('接收到的 type:', type); // 输出: "4"

  loading.value = true;
  queryParams.value.params = {};
  if (route.query?.type && route.query.type == 4) {
    queryParams.value.projectType = '4'
  }

  getAllSaleRole(null).then((response) => {
    saleRoleList.value = response.data
  });

  myJoinProject(queryParams.value).then((response) => {
    console.log("response", response);
    projectList.value = response.data.rows;
    total.value = response.data.total;
    loading.value = false;
    console.log('projectList', projectList);
  });
  loadingCount.value = true
  await myJoinListCount(queryParams.value).then((response) => {
    source.value = response.data.contractAmountTotal;
    source1.value = response.data.settlementAmountTotal;
    source2.value = response.data.receivedTotal
  }).finally(() => {
    loadingCount.value = false
  });

}

// 取消按钮
function cancel() {
  open.value = false;
  openView.value = false
  reset();
  getList()
}


// 表单重置
function reset() {
  form.value = {
    projectNo: null,
    projectName: null,
    createDeptName: null,
    projectAmount: null,
    projectType: null,
    saleRole: null,
    projectUnit: null,
    acceptTime: null,
    customerAddress: null,
    customerName: null,
    housekeeperProject: null,
    phaseCode: null,
    remark: null,
    minProjectAmount: null,
    maxProjectAmount: null,

    companyName: null,
    companyType: null,
    companyNo: null,
    keyWords: null

  };
  proxy.resetForm("projectRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}


/** 重置按钮操作 */
function resetQuery() {
  daterangeAcceptTime.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.minProjectAmount = null
  queryParams.value.maxProjectAmount = null
  handleQuery();
}




function getListParticipan(projectNo) {
  console.log("projectNoprojectNo", projectNo);
  let params = {
    projectNo: projectNo
  }
  listParticipan(params).then((response) => {
    console.log("参与人员信息", response);
    personList.value = response.data
  });

}



import mainList from "../mainList.vue";
import saleList from "../saleList.vue";
import feeList from "../fee.vue"
import compareMainAndSale from "../compareMainAndSale.vue"
import matching from "../matching.vue"
const activeName = ref('first')
function handleClick(item, event) {
  // activeName
  console.log("tabs页面跳转", item.paneName, event)
  activeName.value = item.paneName
}

async function handleView(row) {
  activeName.value = "first"
  formDisabled.value = true
  isView.value = true
  reset();
  getProjectInfo(row.projectNo)
  const _projectNo = row.projectNo || ids.value;
  await getProject(_projectNo).then((response) => {
    form.value = response.data;
    openView.value = true;
  });

}


function getProjectInfo(projectNo) {
  console.log("projectNoprojectNo", projectNo);

  let params = {
    projectNo: projectNo
  }


  //参与人
  listParticipan(params).then((response) => {
    console.log("参与人员", response);
    personList.value = response.data
  });

  //附件
  listAttachment(params).then((response) => {
    attachmentList.value = response.data;
  });

  //付款信息
  listPay(params).then((response) => {
    payList.value = response.data;
  });

  //核算信息
  listAccounting(params).then((response) => {
    accountingList.value = response.data;
  });

  //质保信息
  listWarranty(params).then((response) => {
    warrantyList.value = response.data;
  });

  listImplement(params).then((response) => {
    implementList.value = response.data;
  });



}




getList();
tets()


onMounted(() => {
  loadUserColumnConfig()
  nextTick(() => {
    getList()
  })

});


// 所有可用列配置（可从接口获取）
const allColumns = [
  { label: "项目名称", prop: "projectName", visible: true },
  { label: "发起人", prop: "createUserName", visible: true },
  { label: "合同金额", prop: "contractAmount", visible: true },
  { label: "结算金额", prop: "settlementAmount", visible: true },
  { label: "项目阶段", prop: "phaseName", visible: true },
  { label: "立项日期", prop: "approvalDate", visible: true },
  { label: "上次更新时间", prop: "updateTime", visible: true },
  { label: "预计验收日期", prop: "acceptTime", visible: true },
  { label: "客户名称", prop: "customerName", visible: true },
  { label: "管家婆项目", prop: "housekeeperName", visible: true },
  { label: "项目类型", prop: "projectTypeName", visible: true },
  { label: "阶段确认人", prop: "joinPeople", visible: true },
  { label: "当前操作人", prop: "currentPeople", visible: true },
]

// 用户当前选择的列 props（由 el-checkbox-group 控制）
const selectedProps = ref([])

// 当前可见列列表（根据 selectedProps 排序后的结果）
const visibleColumns = computed(() => {
  return selectedProps.value
    .map(prop => allColumns.find(col => col.prop === prop))
    .filter(Boolean)
})



// 当前可见列（根据用户选择动态变化）
const selectedColumns = ref([...allColumns])


const saveColumnConfig = async () => {

  console.log('保存配置', selectedProps.value);


  // 调用保存到后端的接口
  await saveUserTableConfig({ configs: selectedProps.value, type: "myJoin" })
  proxy.$modal.msgSuccess("保存配置成功");

}

const getWidth = (prop) => {
  switch (prop) {
    case 'projectName':
    case 'approvalDate':
    case 'updateTime':
    case 'acceptTime':
      return 200;
    case 'housekeeperName':
      return 300;
    default:
      return undefined;
  }
}

async function loadUserColumnConfig() {
  const res = await getUserTableConfig({ type: "myJoin" })

  let defaultOrder = allColumns
    .filter(col => col.visible !== false) // 可以根据 visible 控制是否默认显示
    .map(col => col.prop)

  if (res.data && Array.isArray(res.data)) {
    // 使用用户保存的顺序（只保留合法的 prop）
    selectedProps.value = res.data.filter(prop =>
      allColumns.some(col => col.prop === prop)
    )
  } else {
    // 否则使用默认顺序
    selectedProps.value = defaultOrder
  }
}


import useUserStore from '@/store/modules/user'

const userStore = useUserStore()



</script>
<style scoped>
:global(h2#card-usage ~ .example .example-showcase) {
  background-color: var(--el-fill-color) !important;
}


.el-statistic {
  --el-statistic-content-font-size: 28px;
}

/* .statistic-card {
      height: 100%;
      padding: 10px;
      border-radius: 4px;
      background-color: var(--el-bg-color-overlay);
  } */

.statistic-card {
  height: 100%;
  padding-bottom: 20px;
  padding-left: 5vw;
  border-radius: 4px;
  background-color: var(--el-bg-color-overlay);
}

.statistic-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  font-size: 12px;
  color: var(--el-text-color-regular);
  margin-top: 16px;
}

.statistic-footer .footer-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.statistic-footer .footer-item span:last-child {
  display: inline-flex;
  align-items: center;
  margin-left: 4px;
}

.green {
  color: var(--el-color-success);
}

.red {
  color: var(--el-color-error);
}

/* 
  
  :deep(.el-table .warning-row) {
      --el-table-tr-bg-color: var(--el-color-warning-light-9);
  } */

/* 悬停效果 */
/* :deep(.el-table .warning-row:hover td) {
      --el-table-tr-bg-color: var(--el-color-warning-light-8);
      background-color: var(--el-table-tr-bg-color);
  } */

/* 如果需要更醒目的边框样式 */
/* :deep(.el-table .warning-row td) {
      border-bottom: 1px solid var(--el-color-warning-light-5);
      border-top: 1px solid var(--el-color-warning-light-5);
  }
  
  :deep(.el-table .warning-row td:first-child) {
      border-left: 1px solid var(--el-color-warning-light-5);
  }
  
  :deep(.el-table .warning-row td:last-child) {
      border-right: 1px solid var(--el-color-warning-light-5);
  } */



/* 如果需要更醒目的边框样式 */
/* :deep(.el-table .success-row td) {
      border-bottom: 1px solid var(--el-color-warning-light-5);
      border-top: 1px solid var(--el-color-warning-light-5);
  }
  
  :deep(.el-table .success-row td:first-child) {
      border-left: 1px solid var(--el-color-warning-light-5);
  }
  
  :deep(.el-table .success-rowtd:last-child) {
      border-right: 1px solid var(--el-color-warning-light-5);
  } */
</style>